<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 抵扣券操作类
 */
class TicketClass{
	protected $ci;
	private $_db;
	private $_log_db;
	private $price	=	10;
	
	function __construct(){
		$this->ci = & get_instance();

		$this->_db		= $this->ci->load->database('default',true);
		$this->_log_db	= $this->ci->load->database('log',true);
	}

	/**
	 * 加抵扣券
	 * @param array  $data_arr [description]
	 * @param int  $dot 保留位数
	 * @param boolean $addMax  是否变更max_transfer
	 * @param string  $write_conn [description]
	 */
	public function add($data_arr, $dot=2) {
		foreach ($data_arr as $key => $val) {
			$$key = $val;
		}
		unset($data_arr);
		$rs			= false;
		$datetime	= date('Y-m-d H:i:s');
		if(!isset($table) || $table=='') $table = 'user_info';
		if(!isset($ip) || $ip=='') $ip = '127.0.0.1';
		if(!isset($where) || $where=='') $where = array('uid'=>$uid);
		if($use_value<=0){
			return false;
		}
		try {
			$this->_db->set($object, $object.'+'.$use_value, FALSE);
			$this->_db->where($where);
			$this->_db->update($table);
			// 查询现有值
			$query = $this->_db->select()->from($table)->where($where)->limit(1)->get();
			if ($query->row()) {
				$rs = $query->row_array();
			}else throw new Exception('L:'.__LINE__." $table query error!", 1);

			$log_arr = array(
				'action' => 'add',
				'name' => $name,
				'uid' => $uid,
				'old' => bcsub($rs[$object],$use_value,$dot),
				'new' => $rs[$object],
				'use_value' => $use_value,
				'comefrom' => isset($comefrom)?$comefrom:1,
				'source' =>	$source,
				'ip' => $ip,
				'add_time' => $add_time,
				'create_time' => $datetime,
				'status' => 1,
			);
			$logTb = splitTable('log_'.$object, $uid);
			if (!$this->_log_db->insert($logTb, $log_arr)) throw new Exception('L:'.__LINE__." $logTb add insert error!", 1);
			$rs = true;
		} catch (Exception $e) {
			writeDebug('['.$datetime.'] 加'.$object.'失败! Err: '.$e->getMessage(), 'Doing');
		}
		return $rs;
	}


	/**
	 * 扣
	 * @param  array  $data_arr  [description]
	 * @param  boolean $reduceMax 是否变更max_transfer
	 * @param  string  $write_conn [description]
	 * @return [type]              [description]
	 */
	public function reduce($data_arr, $dot=2) {
		foreach ($data_arr as $key => $val) {
			$$key = $val;
		}
		unset($data_arr);
		$rs = false;
		$datetime = date('Y-m-d H:i:s');
		if(!isset($table) || $table=='') $table = 'user_info';
		if(!isset($ip) || $ip=='') $ip = '127.0.0.1';
		if(!isset($where) || $where=='') $where = array('uid'=>$uid,$object.'>='=>$use_value);
		if($use_value<=0){
			return false;
		}
		try {
			$this->_db->set($object, $object.'-'.$use_value, FALSE);
			// $this->_db->set($object.'_block', $object.'_block+'.$use_value, FALSE);
			$this->_db->where($where);
			
			if(!$this->_db->update($table)){
				throw new Exception('L:'.__LINE__." $object reduce update error!", 1);
			}
			// 查询现有值
			$where = array('uid'=>$uid);
			$query = $this->_db->select()->from($table)->where($where)->limit(1)->get();
			if ($query->row()) {
				$rs = $query->row_array();
			}else throw new Exception('L:'.__LINE__." $table query error!", 1);
			
			$log_arr = array(
				'action' => 'reduce',
				'name' => $name,
				'uid' => $uid,
				'old' => bcadd($rs[$object],$use_value,$dot),
				'new' => $rs[$object],
				'use_value' => $use_value,
				'comefrom' => isset($comefrom)?$comefrom:1,
				'source' => $source,
				'ip' => $ip,
				'add_time' => $add_time,
				'create_time' => $datetime,
				'status' => 1,
			);
			$logTb = splitTable('log_'.$object, $uid);
			if (!$this->_log_db->insert($logTb, $log_arr)) throw new Exception('L:'.__LINE__." $table reduce insert error!", 1);
			$rs = true;
		} catch (Exception $e) {
			writeDebug('['.$datetime.'] 扣'.$object.'失败! Err: '.$e->getMessage(), 'Doing');
		}

		return $rs;
	}

	public function buy($data){
		
		// 初始化数据
		foreach($data as $key => $val) {
			$$key = $val;
		}
		unset($data);

		if ($num <=0 || !is_numeric($num) || strpos($num,".")!==false ) return jsonReturn(-1,"购买数量错误",array(),TRUE); 

		$datetime	=	date('Y-m-d H:i:s');
		$use_value	=	bcmul($num,$this->price,2);
		$ip			=	get_ip();
		$source		= '90002';//购买抵扣券

		try {

			//扣款cny处理
			$reduceArr = array(
				'uid' => $uid,
				'name' => 'ACCOUNT',
				'object' => 'cny',
				'use_value' => $use_value,
				'source' => $source,
				'ip' => $ip,
				'add_time' => $datetime,
			);
			if(!$this->reduce($reduceArr)){
				throw new Exception('余额不足，请重新填写数量', 1);
			}

			//加抵扣券处理
			$addArr = array(
				'uid' => $uid,
				'name' => 'ACCOUNT',
				'object' => 'ticket',
				'use_value' => $num,
				'source' => $source,
				'ip' => $ip,
				'add_time' => $datetime,
			);
			if(!$this->add($addArr)){
				throw new Exception('添加抵扣券失败', 1);
			}

			$this->flushUserCache($uid);
		} catch (Exception $e) {
			return jsonReturn(-1,$e->getMessage(),array(),TRUE);
		}
		return jsonReturn(0,"success",array(),TRUE);
	}

	public function getBuyTicketNum($uid,$sdate="",$edate=""){
		$logTb	=	splitTable('cfd_log_ticket', $uid);
		$source	=	"90002";
		$where	=	"where source='$source' and uid ='$uid'";
		$where	.=	!empty($sdate)?" and create_time>='$sdate'":"";
		$where	.=	!empty($edate)?" and create_time<='$edate'":"";
		$sql	=	"select sum(use_value) as num from $logTb ".$where;
		$query	=	$this->_log_db->query($sql);
		$row	=	$query->row_array();
		if(!empty($row)){
			return intval($row['num']);
		}
		return 0;
	}

	public function getBuyTicketCny($uid="",$sdate="",$edate=""){
		$source	=	"90002";
		$where	=	"where source='$source'";
		$where	.=	!empty($uid)?" and uid ='$uid'":"";
		$where	.=	!empty($sdate)?" and create_time>='$sdate'":"";
		$where	.=	!empty($edate)?" and create_time<='$edate'":"";
		
		$cny	=	0;
		if(empty($uid)){	
			$sql	=	"show tables like '%cfd_log_ticket%'";
			$query	=	$this->_log_db->query($sql);
			$tab_arr=	$query->result_array();
			if(!empty($tab_arr)) foreach($tab_arr as $tab){
				$logTb	=	$tab['Tables_in_totoro_log (%cfd_log_ticket%)'];
				$sql	=	"select sum(use_value) as num from $logTb ".$where;
				$query	=	$this->_log_db->query($sql);
				$row	=	$query->row_array();
				if(!empty($row)){
					$cny	=	bcadd(bcmul($row['num'],$this->price,2),$cny,2);
				}
			}

		}else{
			$logTb	=	splitTable('cfd_log_ticket', $uid);
			$sql	=	"select sum(use_value) as num from $logTb ".$where;
			$query	=	$this->_log_db->query($sql);
			$row	=	$query->row_array();
			if(!empty($row)){
				$cny	=	bcmul($row['num'],$this->price,2);
			}
		}

		return $cny;
	}

	public function getBuyTicketAllNum($uid="",$sdate="",$edate=""){
		$source	=	"90002";
		$where	=	"where source='$source'";
		$where	.=	!empty($uid)?" and uid ='$uid'":"";
		$where	.=	!empty($sdate)?" and create_time>='$sdate'":"";
		$where	.=	!empty($edate)?" and create_time<='$edate'":"";
		
		$num	=	0;
		if(empty($uid)){	
			$sql	=	"show tables like '%cfd_log_ticket%'";
			$query	=	$this->_log_db->query($sql);
			$tab_arr=	$query->result_array();
			if(!empty($tab_arr)) foreach($tab_arr as $tab){
				$logTb	=	$tab['Tables_in_cfd_log (%cfd_log_ticket%)'];
				$sql	=	"select sum(use_value) as num from $logTb ".$where;
				$query	=	$this->_log_db->query($sql);
				$row	=	$query->row_array();
				if(!empty($row)){
					$num	=	bcadd($row['num'],$num,2);
				}
			}

		}else{
			$logTb	=	splitTable('cfd_log_ticket', $uid);
			$sql	=	"select sum(use_value) as num from $logTb ".$where;
			$query	=	$this->_log_db->query($sql);
			$row	=	$query->row_array();
			if(!empty($row)){
				$num	=	bcadd($row['num'],$num,2);
			}
		}

		return intval($num);
	}
	
	public function getCnyShare($where){
		$table = "cfd_cny_share";
		$query = $this->_db->select()->from($table)->where($where)->limit(1)->get();
		if ($query->row()){
			return $query->row_array();
		}else{
			return array(); // 无效的操作
		}
	}

	public function getAllShare($sdate,$edate,$type=""){
		$table = "cfd_cny_share";
		if($type){
			$this->_db->where('type', $type);
		}
		$this->_db->where('lastest_modify >=', $sdate);
		$this->_db->where('lastest_modify <=', $edate);
		$query = $this->_db->select()->from($table)->get();
		if ($query->result_array()){
			return $query->result_array();
		}else{
			return array(); // 无效的操作
		}
	}

	public function getAllShareLog($where){
		$table = "ticket_share_log";
		$query = $this->_db->select()->from($table)->where($where)->get();
		if ($query->result_array()){
			return $query->result_array();
		}else{
			return array(); // 无效的操作
		}
	}

	public function checkUserTicketNum($where){
		$table = "user_info";
		$query = $this->_db->select('ticket')->from($table)->where($where)->get();
		if ($query->result_array()){
			return $query->row_array();
		}else{
			return array(); // 无效的操作
		}
	}

	/**
	 * 清用户缓存
	 * @return [type] [description]
	 */
	public function flushUserCache($uid){
		$CI =& get_instance();
        $default_config = array(
            'host' => '127.0.0.1',
            'port' => 6379,
            'timeout' => 0
        );
        if ($CI->config->load('redis', TRUE, TRUE)){
            $config = array_merge($default_config, $CI->config->item('redis'));
        }else{
            $config = $default_config;
        }
        $redis = new Redis();
        $redis->connect($config['host'],$config['port'],$config['timeout']);
        $redis->select(3);
        $rs = $redis->delete("USERINFO|$uid");
	}
}


